package com.dingli.admin.aop;

import com.dingli.framework.entity.User;
import com.dingli.framework.filter.GlobalFilter;
import com.dingli.framework.util.Response;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

@Aspect
@Component
public class SecurityAop {

    @Value("${security.check}")
    private Boolean check;

    @AfterReturning(returning = "result", pointcut = "execution(* com.dingli.admin.service.impl.SystemService.login(..))")
    public void afterReturning(Response<User> result) {
        if (check && result.getData() != null) {
            String token = GlobalFilter.add(result.getData());
            RequestAttributes ra = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes sra = (ServletRequestAttributes) ra;
            HttpServletResponse response = sra.getResponse();
            response.setHeader("Access-Control-Expose-Headers", "token");
            response.setHeader("token", token);

        }
    }

}